package org.september.pisces.filestore.controller;

import java.io.InputStream;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

import lombok.extern.slf4j.Slf4j;
import org.september.core.exception.BusinessException;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.service.FileStoreManager;
import org.september.simpleweb.auth.PublicMethod;
import org.september.simpleweb.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 文件存储池管理
 */
@Slf4j
@Controller
public class FileStoreController extends BaseController {

	
    @Autowired
    private FileStoreManager fileStoreManager;

    @PublicMethod
    @ResponseBody
    @RequestMapping(value = "/pisces/fileStore/getFile")
    public void getFile(HttpServletResponse response, String uuid,Boolean thumb,String fileName) throws Exception {
        thumb= thumb != null && thumb;
    	FileStoreItem item = fileStoreManager.getFileItem(uuid);
    	InputStream ins = null;
        for (int i = 0; i < 7; i++) {
            ins = fileStoreManager.getInputStreamByUUID(item,thumb);
            if (ins == null) {
                log.info("uuid={},没获取到流,500ms后重试,i={}", uuid, i);
                Thread.sleep(500);
            }else {
                break;
            }
        }
        if(ins==null){
            throw new BusinessException("资源还没准备好!");
        }
        if(fileName!=null) {
        	response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.setContentType("application/octet-stream;charset=UTF-8");
        }
    	ServletOutputStream out = response.getOutputStream();
    	String type = URLConnection.guessContentTypeFromName(item.getPath());
    	response.setContentType(type);
    	ins.transferTo(out);
    	ins.close();
    	out.close();
    }
    
    public static final String Get_File_Action = "/pisces/fileStore/getFile";
}
